package com.xxl.job.admin.controller;

import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.admin.controller.annotation.PermissionLimit;
import com.xxl.job.admin.core.model.JobLogModel;
import com.xxl.job.admin.core.model.ProductEnum;
import com.xxl.job.admin.core.model.XxlJobUser;
import com.xxl.job.admin.dao.JobLogDao;
import com.xxl.job.admin.dao.ProductEnumDao;
import com.xxl.job.admin.service.LoginService;
import com.xxl.job.core.util.DateUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cql
 * @date 2021年12月16日 14:39
 */
@Controller
@RequestMapping("/long")
public class LongController {

    @Resource
    private JobLogDao jobLogDao;

    @Resource
    private ProductEnumDao productEnumDao;

    @RequestMapping
//    @PermissionLimit(adminuser = true)
    public String index(Model model) {

        //接口传输类型
        List<ProductEnum> incClassList = productEnumDao.findByValSetId("INC_TRAN_TYPE");
        model.addAttribute("jobClassList", incClassList);
        List<ProductEnum> incResultList = productEnumDao.findByValSetId("INC_TRAN_RESULT");
        model.addAttribute("jobResultList", incResultList);
        return "long/long.index";
    }

    @RequestMapping("/pageList")
    @ResponseBody
//    @PermissionLimit(adminuser = true)
    public Map<String, Object> pageList(HttpServletRequest request, @RequestParam(required = false, defaultValue = "0") int start,
                                        @RequestParam(required = false, defaultValue = "10") int length,
                                        String jobCode, String jobClass, String queryTime, String jobResult) {

        XxlJobUser loginUser = (XxlJobUser) request.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
        // parse param
        Date startTime = null;
        Date endTime = null;
        if (queryTime != null && queryTime.trim().length() > 0) {
            String[] temp = queryTime.split(" - ");
            if (temp.length == 2) {
                startTime = DateUtil.parseDateTime(temp[0]);
                endTime = DateUtil.parseDateTime(temp[1]);
            }
        }
        String userName = "";
        if (loginUser.getUsername().equals("admin")) {
            userName = "-1";
        } else {
            userName = loginUser.getUsername();
        }
        List<JobLogModel> list = jobLogDao.pageList(start, length, jobCode, jobClass, startTime, endTime, userName, jobResult);
        int list_count = jobLogDao.pageListCount(start, length, jobCode, jobClass, startTime, endTime, userName, jobResult);
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("recordsTotal", list_count);        // 总记录数
        maps.put("recordsFiltered", list_count);    // 过滤后的总记录数
        maps.put("data", list);                    // 分页列表
        return maps;
    }

    @RequestMapping("/exportExcel")
    @ResponseBody
    @PermissionLimit(adminuser = true)
    public void exportExcel(String excelparm, HttpServletResponse response) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            String queryparm = URLDecoder.decode(excelparm, "UTF-8");
            Map<String, Object> map = mapper.readValue(queryparm, Map.class);
            Date startTime = null;
            Date endTime = null;
            String queryTime = map.get("queryTime").toString();
            if (queryTime != null && queryTime.trim().length() > 0) {
                String[] temp = queryTime.split(" - ");
                if (temp.length == 2) {
                    startTime = DateUtil.parseDateTime(temp[0]);
                    endTime = DateUtil.parseDateTime(temp[1]);
                }
            }
            queryTime = queryTime.replaceAll(" ", "-");
            String jobClass = map.get("jobClass").toString();
            String jobCode = map.get("jobCode").toString();
            String jobResult = map.get("jobResult").toString();
            List<JobLogModel> list = jobLogDao.pageListAll(jobCode, jobClass, startTime, endTime, jobResult);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            String fileName = URLEncoder.encode("日志信息" + queryTime, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // easyexcel导出工具
            EasyExcel.write(response.getOutputStream(), JobLogModel.class).autoCloseStream(Boolean.FALSE).sheet("日志信息")
                    .doWrite(list);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
